package cn.medemede.beans;

import cn.medemede.dao.DatabaseConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.sql.*;

public class Log_check implements Action,Serializable{

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String farward = "log_failed";
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        System.out.println("username:" + username);
        String password = request.getParameter("password");
        System.out.println("password:" + password);
        String code = (String) request.getSession().getAttribute("code");
        code=code.toLowerCase();
        System.out.println("code:" + code);
        String icode = request.getParameter("checkcode");
        icode=icode.toLowerCase();
        System.out.println("checkcode:" + icode);

        if (code.equals(icode)) {
            System.out.println("验证码正确！");
            String sql = "select * from users where username='" + username + "' and password='" + password + "'";
            Connection connection = null;
            try {
                connection = DatabaseConnection.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("错误！------数据库连接失败！");
                out.println("---错误！------数据库连接失败！---");
            }
            try {
                System.out.println("connection验证！");
                if (connection != null) {
                    System.out.println("-------数据库连接成功！-------");
                    out.println("---数据库连接成功！----");
                    Statement statement = connection.createStatement();
                    ResultSet rs = statement.executeQuery(sql);
                    if (rs.next()) {
                        farward = "log_suc";
                        request.getSession().setAttribute("username", request.getParameter("username"));
                    } else {
                        System.out.println("密码错误或用户不存在!");
                        out.println("---密码错误或用户不存在!---");
                        farward = "log_failed";
                    }
                    DatabaseConnection.releaseResources(rs, statement, connection);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            farward="验证码错误！";
        }
        return farward;
    }
}
